import Vue from 'vue'
import VueRouter from 'vue-router'
import Reg from '../views/Reg/Reg.vue'
import Login from '../views/Login/Login.vue'
import Main from '../views/Main/Main.vue'
import store from '../store'
import Home from '../views/Main/Home/Home.vue'
import UserInfo from '../views/Main/User/UserInfo.vue'
import UserAvatar from '../views/Main/User/UserAvatar.vue'
import UserPwd from '../views/Main/User/UserPwd.vue'
import ArtCate from '../views/Main/Article/ArtCate.vue'
import ArtList from '../views/Main/Article/ArtList.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      { path: 'home', component: Home },
      { path: '/user-info', component: UserInfo },
      { path: '/user-avatar', component: UserAvatar },
      { path: '/user-pwd', component: UserPwd },
      { path: '/art-cate', component: ArtCate },
      { path: '/art-list', component: ArtList }
    ]
  }
]

const router = new VueRouter({

  routes
})

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  const arr = ['/login', '/reg']
  if (!store.state.user.token && !arr.includes(to.path)) {
    next('/login')
  }
  next()
})

export default router
